import axios from 'axios';
import { useCurrentUserStore } from '@/modules/security/stores/currentUserStores';
import router from '@/modules/common/router'; // 导入路由

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_API,
  timeout: 5000,
});

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const userStore = useCurrentUserStore();
    const token = userStore.currentUser?.Authorization;
    config.headers['Content-Type'] = 'application/json';
    if (token) {
      config.headers['Authorization'] = token;
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    if (response.data.code>=200 && response.data.code<300){
      return response.data;
    }else{
      return Promise.reject(new Error(response.data.message));
    }
  },
  (error) => {
    if (
      !router.currentRoute.value.meta.noAuth
      && error.response
      && error.response.status === 401
    ) {
      return router.push('/login');
    }
    return Promise.reject(new Error(error.message));
  },
);

export default service;
